#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理

void MainWindow::modifyCameraStatusFile(bool powerOn)
{
    QString filePath = "/home/shenxiuqi/Desktop/camera.status";  // camera.status路径
    QFile file(filePath);

    if (!file.exists()) {
        qDebug() << "Error: File not found";
        return;
    }

    // 读取文件内容
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Error: Cannot open file for reading";
        return;
    }

    QStringList lines;
    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine();
        if (line.startsWith("power_status=")) {
            line = QString("power_status=%1").arg(powerOn ? "1" : "0");
        }
        lines.append(line);
    }
    file.close();

    // 写入修改后的内容
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "Error: Cannot open file for writing";
        return;
    }

    QTextStream out(&file);
    foreach (const QString &line, lines) {
        out << line << "\n";
    }
    file.close();

    qDebug() << "Power status updated to:" << (powerOn ? "1" : "0");
}

void MainWindow::initializeLogSystem() {
    // 确保日志目录存在
    QDir().mkpath(m_logDirectory);

    // 初始化日志文件
    QStringList logFileNames = {
        "camera_control.log",    // 相机控制日志
        "camera_ps.log",
        "temp_vacuum.log",       // 温控真空日志
        "alarm.log",             // 报警日志
        "general.log",           // 常规日志
        "debug.log"              // 调试日志
    };

    for (int i = 0; i < logFileNames.size(); ++i) {
        LogCategory category = static_cast<LogCategory>(i);
        QString filePath = m_logDirectory + "/" +
                           QDateTime::currentDateTime().toString("yyyyMMdd_") +
                           logFileNames[i];

        QFile* logFile = new QFile(filePath);
        if (!logFile->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
            qWarning() << "无法打开日志文件:" << filePath;
            continue;
        }

        m_logFiles[category] = logFile;
        m_logStreams[category] = new QTextStream(logFile);
        m_logStreams[category]->setCodec("UTF-8");

        // 写入日志文件头
        *m_logStreams[category] << QString("===== 日志开始 [%1] =====\n")
                                       .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    }

    // 设置定时刷新缓冲区(每5秒)
    m_logFlushTimer.setInterval(5000);
    connect(&m_logFlushTimer, &QTimer::timeout, this, [this](){
        QMutexLocker locker(&m_logMutex);
        for (auto stream : m_logStreams) {
            stream->flush();
        }
        for (auto file : m_logFiles) {
            file->flush();
        }
    });
    m_logFlushTimer.start();
}

void MainWindow::writeAutoUpdateLog(const QString &message)
{
    if (m_autoUpdateLogFile.isOpen()) {
        QTextStream stream(&m_autoUpdateLogFile);
        stream << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss] ")
               << message << "\n";
    }
}
void MainWindow::writeLog(LogCategory category, const QString& level,
                          const QString& location, const QString& message,
                          bool showInUI) {
    QMutexLocker locker(&m_logMutex);
    // 确保日志类别有效
    if (!m_logFiles.contains(category) || !m_logStreams.contains(category)) {

        qWarning() << "无效的日志类别:" << category;
        return;
    }
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    QString fullMessage = QString("[%1][%2][%3] %4\n") .arg(timestamp) .arg(level) .arg(location) .arg(message);
    // 写入对应类别的日志文件
    *m_logStreams[category] << fullMessage;
    // 如果是错误日志，立即刷新
    if (level == "ERROR") {

        m_logStreams[category]->flush();
        m_logFiles[category]->flush(); }
    // 根据标志决定在哪个UI中显示
    if (showInUI) {
        // 在主线程更新UI
        QMetaObject::invokeMethod(this, [this, fullMessage, category]() {
            if (category == CAMERA_LOG || category == GENERAL_LOG) {
                ui->textEditCameraLog->appendPlainText(fullMessage);
            } else if(category == CAMERAPS_LOG)
            {
                ui->textEditSecondLog->appendPlainText(fullMessage);
            }
        }, Qt::QueuedConnection);
    }
}

void MainWindow::writeLogx(LogCategory category, const QString& level,
                          const QString& location, const QString& message,
                          bool showInUI) {
    QMutexLocker locker(&m_logMutex);

    // 确保日志类别有效
    if (!m_logFiles.contains(category) || !m_logStreams.contains(category)) {
        qWarning() << "无效的日志类别:" << category;
        return;
    }

    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    QString fullMessage = QString("[%1][%2][%3] %4\n")
                              .arg(timestamp)
                              .arg(level)
                              .arg(location)
                              .arg(message);

    // 写入对应类别的日志文件
    *m_logStreams[category] << fullMessage;

    // 如果是错误日志，立即刷新
    if (level == "ERROR") {
        m_logStreams[category]->flush();
        m_logFiles[category]->flush();
    }

    // 根据标志决定是否在UI中显示
    if (showInUI) {
        // 在主线程更新UI
        QMetaObject::invokeMethod(this, [this, fullMessage]() {
            ui->textEditCameraLog->appendPlainText(fullMessage);
        }, Qt::QueuedConnection);
    }
}

void MainWindow::threadSafeLog(const QString& level, const QString& message) {
    QMetaObject::invokeMethod(this, [this, level, message]() {
        QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");
        QString logMsg = QString("[%1][%2] %3").arg(timestamp, level, message);

        // UI操作必须在主线程执行
        //ui->textEditCameraLog->appendPlainText(logMsg);

        // 文件写入需要加锁
        QMutexLocker locker(&logMutex);
        if (m_logFile.isOpen()) {
            m_logStream << logMsg << "\n";
        }
    });
}

void MainWindow::checkAndRotateLogFiles()
{
    QMutexLocker locker(&m_logMutex);

    QString currentDate = QDateTime::currentDateTime().toString("yyyyMMdd");

    for (auto category : m_logFiles.keys()) {
        QString filePath = m_logFiles[category]->fileName();
        QString fileDate = filePath.mid(filePath.lastIndexOf('_') - 8, 8);

        if (fileDate != currentDate) {
            // 关闭旧文件
            m_logStreams[category]->flush();
            m_logFiles[category]->close();

            // 创建新文件
            QString newFilePath = m_logDirectory + "/" + currentDate + "_" +
                                  filePath.mid(filePath.lastIndexOf('_') + 1);

            m_logFiles[category]->setFileName(newFilePath);
            if (!m_logFiles[category]->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
                qWarning() << "无法创建新的日志文件:" << newFilePath;
                continue;
            }

            *m_logStreams[category] << QString("[%1] 创建新的日志文件\n")
                                           .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
        }
    }
}
